<?php

class RoleController extends Controller_Base
{

    public function init()
    {
        parent::init();
    }

    /**
     * 角色权限列表
     */
    public function indexAction()
    {
        $request = $this->getRequest();
        $pn = intval($request->getQuery('page', 1));
        $pageQuery = [];
        $whereQuery = [
            'id != 1'
        ];
        $pageSize = 10;
        $pn = $pn ? $pn : 1;
        $start = ($pn - 1) * $pageSize;
        $total = Module_User_Role::getInstance()->getAllBySearch(['count(id) as total'], ['where' => $whereQuery]);
        $total = $total[0]['total'];
        //计算分页
        $totalPage = ceil($total / $pageSize);
        if ($pn > $totalPage && $totalPage > 0) {
            $this->redirect('/role/index?page=' . $totalPage);
            exit;
        }
        $list = Module_User_Role::getInstance()->getAllBySearch(['*'], array('where' => $whereQuery, 'start' => $start, 'order' => 'id ASC', 'limit' => 10));
        
        SmartyAdapter::assign('totalPage', $totalPage);
        SmartyAdapter::assign('totalnum', $total);
        SmartyAdapter::assign('pagesize', $pageSize);
        SmartyAdapter::assign('curPageNum', $pn);
        SmartyAdapter::assign('page_query', http_build_query($pageQuery));
        SmartyAdapter::assign('list', $list);
        SmartyAdapter::$templateName = 'role/index';
    }

    /**
     * 删除角色权限
     */
    public function delAction()
    {
        $request = $this->getRequest();
        $id = intval($request->getPost('id'));
        $actionData = array(
            'source_type' => '1',
            'action_type' => '11',
            'action_time' => time(),
            'action_uid' =>$this->admin['id'],
            'action_uname' => $this->admin['name'],
            'mobile' => $this->admin['mobile'],
            'action_group' => $this->admin['role_id'],
            'action_des' => '删除角色,id为:'.$id,
            'action_res' => '1',
            'action_main' => 'role',
            'action_event' => 'del',
        );
        if (empty($id)) {
            $actionData['action_res'] = 0;
            @Module_Uaction_Hook::onActionData($actionData);
            AjaxTool::returnJsonData(4001, Setup_Error::getConfig(4001), []);
        }
        $role = Module_User_Role::getInstance()->getRoleById($id);
        if (!$role) {
            $actionData['action_res'] = 0;
            @Module_Uaction_Hook::onActionData($actionData);
            AjaxTool::returnJsonData(6000, Setup_Error::getConfig(6000), []);
        }
        if ($id == 1) {
            $actionData['action_res'] = 0;
            @Module_Uaction_Hook::onActionData($actionData);
            AjaxTool::returnJsonData(6005, Setup_Error::getConfig(6005), []);
        }
       /* $check_update = $this->checkHasUpdate($role['id'], $provMaps);
        if (!$check_update) {
            $actionData['action_res'] = 0;
            @Module_Uaction_Hook::onActionData($actionData);
            AjaxTool::returnJsonData(4001, '有尚未处理的案件，无法修改', []);
        }*/
        // 查询该权限有无用户
        $admin = Module_User_Administrator::getInstance()->getAdminByRoleId($id);
        if ($admin) {
            $actionData['action_res'] = 0;
            @Module_Uaction_Hook::onActionData($actionData);
            AjaxTool::returnJsonData(6001, Setup_Error::getConfig(6001), []);
        }
        $delRes = Module_User_Role::getInstance()->deleteById($id);
        if (!$delRes) {
            $actionData['action_res'] = 0;
            @Module_Uaction_Hook::onActionData($actionData);
            AjaxTool::returnJsonData(4000, Setup_Error::getConfig(4000), []);
        }

        @Module_Uaction_Hook::onActionData($actionData);
        AjaxTool::returnJsonData(200, Setup_Error::getConfig(200), []);
    }

    /**
     * 添加角色权限
     */
    public function addAction()
    {
        SmartyAdapter::$templateName = 'role/add';
        $request = $this->getRequest();
        $role = $request->getPost('role');
        if (!empty($role)) {
            $actionData = array(
                'source_type' => '1',
                'action_type' => '9',
                'action_time' => time(),
                'action_uid' =>$this->admin['id'],
                'action_uname' => $this->admin['name'],
                'mobile' => $this->admin['mobile'],
                'action_group' => $this->admin['role_id'],
                'action_des' => '添加角色',
                'action_res' => '1',
                'action_main' => 'role',
                'action_event' => 'add',
            );
            foreach ($role as $key => $value) {
                if (is_array($value)) {
                    foreach ($value as $k => $val) {
                        $value[$key] = trim($val);
                    }
                } else {
                    $role[$key] = trim($value);
                }
            }
            if (!isset($role['title']) || !$role['title']) {
                AjaxTool::returnJsonData(6002, Setup_Error::getConfig(6002), []);
            }
            $check = Module_User_Role::getInstance()->getByTitle($role['title']);
            if ($check) {
                AjaxTool::returnJsonData(6004, Setup_Error::getConfig(6004), []);
            }

            if (!isset($role['provisioning']) || !$role['provisioning']) {
                AjaxTool::returnJsonData(6003, Setup_Error::getConfig(6003), []);
            }
            $arrPostProvi = array();
            foreach ($role['provisioning'] as $val) {
                if (intval($val > 0)) {
                    $arrPostProvi[] = intval($val);
                }
            }
            if (!empty($arrPostProvi)) {
                $saveData = [
                    'title' => addslashes($role['title']),
                    'provisioning' => implode(',', $arrPostProvi),
                    'add_time' => time(),

                ];

                $retId = Module_User_Role::getInstance()->insertData($saveData);
                if (!$retId) {
                    $actionData['action_des'] =  '添加角色失败';
                    $actionData['action_res'] =  0;
                    @Module_Uaction_Hook::onActionData($actionData);
                    AjaxTool::returnJsonData(4000, Setup_Error::getConfig(4000), []);
                }
                $actionData['action_des'] =  '添加角色'.$retId;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(200, Setup_Error::getConfig(200), []);
            }
            AjaxTool::returnJsonData(4000, Setup_Error::getConfig(4000), []);
        }
        $roleList = Module_User_Provisioning::getInstance()->getListAll();

        $roleListArr = array();
        foreach ($roleList as $_info) {
            $roleListArr[$_info['parent_id']][] = $_info;
        }

        $role_list = array();
        foreach ($roleListArr[0] as $_info) {
            $_id = $_info['id'];
            if (isset($roleListArr[$_id])) {
                $role_list[$_id] = $_info;

                $role_list[$_id]['data'] = $roleListArr[$_id];
                foreach ($role_list[$_id]['data'] as $k1=>$v1){
                    $role_list[$_id]['data_new'][$v1['c_parent']][] = $v1;
                }
                unset($role_list[$_id]['data']);

            }
        }
      //  Func_Log::write("test11", '$roleListArr' , var_export($role_list, true));
        SmartyAdapter::assign('arrProvisions', $role_list);
    }

    /**
     * 编辑角色权限
     */
    public function editAction()
    {

        $request = $this->getRequest();
        $id = intval($request->getQuery('id'));
        if (!$id) {
            $this->displayError('非法请求', '/role/index');
        }
        $roleInfo = Module_User_Role::getInstance()->getRoleById($id);
        if (!$roleInfo) {
            $this->displayError('权限组不存在，请确认~', '/role/index');
        }

        //权限列表
        $provMaps = explode(",",$roleInfo['provisioning']) ;

        $role = $request->getPost('role');
        if (!empty($role)) {
            if (empty($id)) {
                $this->displayError('参数错误', '/role/index');
            }
            foreach ($role as $key => $value) {
                if (is_array($value)) {
                    foreach ($value as $k => $val) {
                        $value[$key] = trim($val);
                    }
                } else {
                    $role[$key] = trim($value);
                }
            }
            $actionData = array(
                'source_type' => '1',
                'action_type' => '10',
                'action_time' => time(),
                'action_uid' =>$this->admin['id'],
                'action_uname' => $this->admin['name'],
                'mobile' => $this->admin['mobile'],
                'action_group' => $this->admin['role_id'],
                'action_des' => '编辑角色id为'.$role['id'],
                'action_res' => '1',
                'action_main' => 'role',
                'action_event' => 'edit',
            );
            if (!isset($role['title']) || !$role['title']) {
                $actionData['action_res'] =  0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(6002, Setup_Error::getConfig(6002), []);
            }
            $check = Module_User_Role::getInstance()->getByTitle($role['title']);
            if ($check && $check['id'] != $id) {
                $actionData['action_res'] =  0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(6004, Setup_Error::getConfig(6004), []);
            }
            if (!isset($role['provisioning']) || !$role['provisioning']) {
                $actionData['action_res'] =  0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(6003, Setup_Error::getConfig(6003), []);
            }
            if (!$role['id']) {
                $actionData['action_res'] =  0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(4001, Setup_Error::getConfig(4001), []);
            }

            $role['title'] = addslashes($role['title']);
            $roleInfo = Module_User_Role::getInstance()->getRoleById($role['id']);
            if (!$roleInfo) {
                $actionData['action_res'] =  0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(4005, Setup_Error::getConfig(4005), []);
            }
            $titleRes = Module_User_Role::getInstance()->getByTitle($role['title']);
            if ($titleRes && $titleRes['id'] != $roleInfo['id']) {
                $actionData['action_res'] =  0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(6003, Setup_Error::getConfig(6003), []);
            }
            $arrPostProvi = array();
            foreach ($role['provisioning'] as $val) {
                if (intval($val > 0)) {
                    $arrPostProvi[] = intval($val);
                }
            }

            if (!empty($arrPostProvi)) {
                $saveData = [
                    'id' => $roleInfo['id'],
                    'title' => $role['title'],
                    'provisioning' => implode(",",$arrPostProvi),
                ];
                $retId = Module_User_Role::getInstance()->updateItemById($saveData);
                if (!$retId) {
                    $actionData['action_res'] =  0;
                    @Module_Uaction_Hook::onActionData($actionData);
                    AjaxTool::returnJsonData(4000, Setup_Error::getConfig(4000), []);
                }
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(200, Setup_Error::getConfig(200), []);
            }
            AjaxTool::returnJsonData(4000, Setup_Error::getConfig(4000), []);
        }else{
            //$roleList = Module_User_RoleGroup::getInstance()->getListAll();
            $roleList = Module_User_Provisioning::getInstance()->getListAll();

            $roleListArr = array();
            foreach ($roleList as $_info) {
                $roleListArr[$_info['parent_id']][] = $_info;
            }
            $role_list = array();
            foreach ($roleListArr[0] as $_info) {
                $_id = $_info['id'];
                if (isset($roleListArr[$_id])) {
                    $role_list[$_id] = $_info;

                    $role_list[$_id]['data'] = $roleListArr[$_id];
                    foreach ($role_list[$_id]['data'] as $k1=>$v1){
                        $role_list[$_id]['data_new'][$v1['c_parent']][] = $v1;
                    }
                    unset($role_list[$_id]['data']);
                }
            }
        }
   
        SmartyAdapter::assign('arrProvisions', $role_list);
        SmartyAdapter::assign('arrUserProv', $provMaps);
        SmartyAdapter::assign('roleInfo', $roleInfo);
    }

    /**
     * 检测该权限组下是否有案件
     */
    private function checkHasUpdate($role_id = 1, $diff = array()) {
        if (!$role_id) {
            return false; //不可修改
        }
        //有变更的数据
        if (!$diff) {
            return true;
        }
        $users = Module_User_Administrator::getInstance()->getByRoleId($role_id, 1);
        if (!$users) {
            return true; //可修改
        }
        $user_ids = array_column($users, 'id');
        if (!$user_ids) {
            return false;
        }
        
        $status = array(1, 2, 4, 5, 7, 8, 9, 12);
        $where = " adm_id in (" . implode(',', $user_ids) . ") and case_status in (" . implode(',', $status) . ")";
        $res = Module_Mediate_Case::getInstance()->getDataByChangeWhere($where);
        if ($res) {
            return false;
        }
        return true;
    }

}